﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.Sql;

namespace RestaurantManagerWebApp.Pages.StockManagement
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            int rows_affected = 0;

            String itemName = txtItemName.Text;
            Decimal qty = Convert.ToDecimal(txtQty.Text);
            int metric_id = Convert.ToInt32(ddlMetric.SelectedValue);       // m_id from Metrics Table
            int category_id = Convert.ToInt32(ddlCategory.SelectedValue);   // c_id from Category Table

            SqlConnection conn = GetConnection();
            conn.Open();

            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;

                cmd.CommandText = "INSERT INTO Ingredient (i_name, i_quantity, m_id, c_id) VALUES (@itemName, @qty, @m_id, @c_id)";
                cmd.Parameters.AddWithValue("@itemName", itemName);
                cmd.Parameters.AddWithValue("@qty", qty);
                cmd.Parameters.AddWithValue("@m_id", metric_id);
                cmd.Parameters.AddWithValue("@c_id", category_id);

                rows_affected = cmd.ExecuteNonQuery();
                
                if(rows_affected > 0)
                {
                    Response.Write("<script type=\"text/javascript\">alert('Item Added Successfully!');</script>");
                }

            }
            catch (SqlException ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                conn.Close();
                txtItemName.Text = "";
                txtQty.Text = "";
                ddlCategory.SelectedIndex = 0;
                ddlMetric.SelectedIndex = 0;
            }
        }
        private SqlConnection GetConnection()
        {
            SqlConnection conn = new SqlConnection(connection);
            return conn;
        }
    }
}